<?php

namespace app\models\auth_app\pinduoduo;

use app\components\Func;
use app\models\AuthOrder;
use app\models\AuthOrderSource;
use app\models\AuthShop;
use Yii;
use app\models\AuthApp;

class AuthAppPinduoduoOrder extends AuthAppPinduoduo
{
    protected $rel_order_status = [
        1 => 1,
        2 => 2,
        3 => 3,
    ];
    //同步订单列表
    public function syncOrders(AuthShop $authShop,$start_time,$end_time,$order_status,$refund_status){
        $query_arr = [
            'type'=>'pdd.order.basic.list.get',
            'access_token'=>$authShop->token,
            'start_confirm_at'=>$start_time,
            'end_confirm_at'=>$end_time,
            'order_status'=>$order_status,
            'refund_status'=>$refund_status,
//            'trade_type'=>'',
            'page'=>1,
            'page_size'=>100,
            'use_has_next'=>1,
        ];
        $cols = ['auth_shop_id','auth_app_order_id','content'];
        $cols2 = ['auth_app_id','auth_shop_id','auth_app_order_id','status'];
        while(1){
            $data = $this->getData($query_arr);
            if(!isset($data['order_list'])) return;
            $rows = [];
            $rows2 = [];
            foreach ($data['order_list'] as $arr) {
                $rows[] = [
                    $authShop->id,
                    $arr['order_sn'],
                    json_encode($arr,JSON_UNESCAPED_UNICODE),
                ];
                $rows2[] = [
                    $authShop->auth_app_id,
                    $authShop->id,
                    $arr['order_sn'],
                    $this->rel_order_status[$arr['order_status']]?:0,
                ];
            }
            $sql = Yii::$app->db->getQueryBuilder()->batchInsert(AuthOrderSource::tableName(), $cols, $rows);
            $sql .= '  ON DUPLICATE KEY UPDATE 
                content=VALUES(content)
            ';
            Yii::$app->db->createCommand($sql)->execute();
            $sql2 = Yii::$app->db->getQueryBuilder()->batchInsert(AuthOrder::tableName(), $cols2, $rows2);
            $sql2 .= '  ON DUPLICATE KEY UPDATE 
                status=VALUES(status)
            ';
            Yii::$app->db->createCommand($sql2)->execute();
            $query_arr['page']++;
            if(!$data['has_next']) return;
        }
    }

}
